<template>
  <div class="login-container">
    <el-form
        :model="loginForm"
        :rules="rules"
        ref="loginForm"
        class="login-form"
        @submit.prevent="onSubmit"
    >
      <h2>登录</h2>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" autocomplete="off" type="password" />
      </el-form-item>
      <el-form-item class="button-row">
        <el-button type="primary" @click="onSubmit" class="login-button">
          <el-icon><Pointer /></el-icon>登录
        </el-button>
        <el-button @click="goToRegister" class="register-button">
          <el-icon><UserFilled /></el-icon>注册
        </el-button>
      </el-form-item>

      <!-- 新增的 vx 登录链接 -->
      <div class="vx-login-link">
        <a @click="loginWithvx">vx 登录</a>
      </div>

      <!-- 微信登录二维码显示 -->
      <div v-if="qrCodeUrl" class="qr-code-container">
        <img :src="qrCodeUrl" alt="微信登录二维码" class="qr-code" />
      </div>

      <!-- 微信登录二维码弹窗 -->
      <el-dialog
          :visible.sync="dialogVisible"
          title="微信登录"
          width="30%"
          @close="handleClose"
      >
        <div style="text-align: center;">
          <img :src="qrCodeUrl" alt="微信二维码" v-if="qrCodeUrl" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>

    </el-form>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { UserFilled, Pointer } from '@element-plus/icons-vue';

export default {
  name: 'Login',
  components: {
    UserFilled,
    Pointer
  },
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      qrCodeUrl: null, // 用于存储微信二维码的 URL
      dialogVisible: false, // 控制弹窗显示状态
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    onSubmit() {
      console.log('Submit button clicked');
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          axios.post('/user/login', this.loginForm)
              .then(response => {
                if (response.data.code === 0) {
                  localStorage.setItem('token', response.data.data); // 使用 localStorage
                  localStorage.setItem('username', this.loginForm.username); // 使用 localStorage
                  ElMessage.success('登录成功');
                  this.connectWebSocket(); // 登录成功后连接 WebSocket
                  this.$router.replace('/chat');
                } else {
                  ElMessage.error(response.data.message);
                }
              })
              .catch(() => {
                ElMessage.error('登录失败');
              });
        } else {
          ElMessage.error('表单验证失败');
        }
      });
    },
    connectWebSocket() {
      const username = localStorage.getItem('username'); // 从 localStorage 获取用户名
      if (username) { // 确保用户名存在
        const socket = new WebSocket(`ws://localhost:8090/xinghuo/chat-websocket?username=${username}`);
        socket.onopen = () => {
          console.log('WebSocket connection established.');
        };
        socket.onerror = (error) => {
          console.error('WebSocket error', error);
        };
        socket.onmessage = (message) => {
          console.log('WebSocket message received:', message.data);
        };
        socket.onclose = () => {
          console.log('WebSocket connection closed.');
        };
      } else {
        console.error('WebSocket connection failed: username is null.');
      }
    },
    goToRegister() {
      this.$router.push('/register');
    },
    loginWithvx() {
      // 发送请求到后端 /wxLogin 接口，并处理二维码显示
      axios.get('/wxLogin', { responseType: 'blob' })
          .then(response => {
            const url = URL.createObjectURL(response.data);
            this.qrCodeUrl = url; // 将生成的二维码图像 URL 存储在 qrCodeUrl 中
            this.dialogVisible = true; // 打开弹窗显示二维码
            console.log('微信登录二维码已生成');
          })
          .catch(error => {
            console.error('微信登录请求失败', error);
            ElMessage.error('微信登录失败');
          });
    },
    handleClose() {
      // 关闭弹窗时的一些处理逻辑（如果有的话）
      this.qrCodeUrl = ''; // 清空二维码 URL
    }
  }
};
</script>
<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url('@/assets/background.jpg') no-repeat center center;
  background-size: cover;
}

.login-form {
  background-color: rgba(255, 255, 255, 0.9);
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  width: 400px;
}

.login-form h2 {
  text-align: center;
  margin-bottom: 25px;
  color: #333;
  font-weight: bold;
  font-size: 24px;
}

.button-row {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.login-button, .register-button {
  width: 120px;
  border-radius: 8px;
  padding: 10px;
  font-weight: bold;
  font-size: 16px;
  text-align: center;

}

.login-button {
  background-color: #2dcbcb;
  color: #fff;
}

.register-button {
  background-color: #47cf2d;
  color: #fff;
}

.vx-login-link {
  text-align: center;
  margin-top: 20px;
}

.vx-login-link a {
  color: #1c88e5;
  text-decoration: none;
  font-weight: bold;
  font-size: 16px;
  cursor: pointer;
}

.vx-login-link a:hover {
  text-decoration: underline;
}

.qr-code-container {
  text-align: center;
  margin-top: 20px;
}

.qr-code {
  width: 200px;
  height: 200px;
}
</style>
